{% extends "learning/base.html" %}

{% block title %}{% if is_edit %}编辑笔记{% else %}新建笔记{% endif %}{% endblock %}

{% block extra_head %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/quill@1.3.7/dist/quill.snow.css">
<style>
    #quill-editor {
        border:1px solid var(--border-subtle);
        border-radius:var(--radius-lg);
        background:var(--surface-elevated);
        min-height:280px;
    }
    .note-mistake-list {
        display:grid;
        gap:0.75rem;
        max-height:280px;
        overflow:auto;
    }
    .note-mistake-list article {
        border:1px solid var(--border-subtle);
        border-radius:var(--radius-md);
        padding:0.75rem;
        background:var(--surface-elevated);
    }
    .note-gallery {
        display:grid;
        gap:1rem;
        grid-template-columns:repeat(auto-fit, minmax(160px, 1fr));
    }
    .note-gallery figure {
        margin:0;
        background:var(--surface-elevated);
        border:1px solid var(--border-subtle);
        border-radius:var(--radius-md);
        overflow:hidden;
        display:flex;
        flex-direction:column;
        gap:0.5rem;
    }
    .note-gallery img {
        width:100%;
        height:140px;
        object-fit:cover;
    }
</style>
{% endblock %}

{% block content %}
<section class="card">
    <div style="margin-bottom:1.5rem;">
        <h2 style="margin:0 0 0.25rem 0;font-size:1.75rem;font-weight:700;">
            {% if is_edit %}编辑笔记{% else %}新建笔记{% endif %}
        </h2>
        <p style="margin:0;color:var(--text-secondary);font-size:0.95rem;">
            使用富文本编辑器撰写学习心得，可上传图片并插入错题链接。
        </p>
    </div>

    <form id="notebook-form" method="post" enctype="multipart/form-data" style="display:grid;gap:1.5rem;">
        {% csrf_token %}
        {% if form.non_field_errors %}
            <div class="message message-error">
                {% for error in form.non_field_errors %}{{ error }}{% endfor %}
            </div>
        {% endif %}

        <div>
            <label for="{{ form.title.id_for_label }}" style="display:block;margin-bottom:0.5rem;font-weight:600;">
                {{ form.title.label }}
            </label>
            {{ form.title }}
            {% for error in form.title.errors %}
                <small style="display:block;color:var(--danger);margin-top:0.375rem;">{{ error }}</small>
            {% endfor %}
        </div>

        <div>
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:0.5rem;gap:1rem;flex-wrap:wrap;">
                <label style="font-weight:600;">{{ form.content.label }}</label>
                <span style="color:var(--text-tertiary);font-size:0.85rem;">支持加粗、列表、引用等格式</span>
            </div>
            <div id="quill-editor"></div>
            {{ form.content }}
            {% for error in form.content.errors %}
                <small style="display:block;color:var(--danger);margin-top:0.375rem;">{{ error }}</small>
            {% endfor %}
        </div>

        <div>
            <label style="display:block;margin-bottom:0.5rem;font-weight:600;">图片附件</label>
            {{ form.attachments }}
            {% if form.attachments.help_text %}
                <small style="display:block;color:var(--text-secondary);margin-top:0.375rem;">
                    {{ form.attachments.help_text }}
                </small>
            {% endif %}
            {% for error in form.attachments.errors %}
                <small style="display:block;color:var(--danger);margin-top:0.375rem;">{{ error }}</small>
            {% endfor %}

            {% if attachments %}
            <div style="margin-top:1rem;">
                <h4 style="margin:0 0 0.75rem 0;font-size:1rem;">已上传图片</h4>
                <div class="note-gallery">
                    {% for attachment in attachments %}
                    <figure>
                        <img src="{{ attachment.image.url }}" alt="笔记图片 {{ forloop.counter }}">
                        <figcaption style="padding:0 0.75rem 0.75rem;">
                            <label style="display:flex;align-items:center;gap:0.5rem;font-size:0.85rem;">
                                <input type="checkbox" name="remove_attachments" value="{{ attachment.pk }}">
                                删除这张图片
                            </label>
                        </figcaption>
                    </figure>
                    {% endfor %}
                </div>
            </div>
            {% endif %}
        </div>

        <div>
            <label for="{{ form.related_mistakes.id_for_label }}" style="display:block;margin-bottom:0.5rem;font-weight:600;">
                {{ form.related_mistakes.label }}
            </label>
            {{ form.related_mistakes }}
            {% if form.related_mistakes.help_text %}
                <small style="display:block;color:var(--text-secondary);margin-top:0.375rem;">
                    {{ form.related_mistakes.help_text }}
                </small>
            {% endif %}
            {% for error in form.related_mistakes.errors %}
                <small style="display:block;color:var(--danger);margin-top:0.375rem;">{{ error }}</small>
            {% endfor %}
        </div>

        {% if mistake_options %}
        <div>
            <h3 style="margin:0 0 0.75rem 0;font-size:1.1rem;">快速插入错题引用</h3>
            <p style="margin:0 0 0.75rem 0;color:var(--text-secondary);font-size:0.9rem;">
                点击“插入链接”即可在编辑区中插入指向错题详情的引用块。
            </p>
            <div class="note-mistake-list">
                {% for mistake in mistake_options %}
                <article>
                    <div style="display:flex;justify-content:space-between;gap:0.75rem;align-items:flex-start;">
                        <div>
                            <strong style="display:block;margin-bottom:0.25rem;color:var(--text-primary);">{{ mistake.title }}</strong>
                            <small style="display:block;color:var(--text-tertiary);">
                                最近更新：{{ mistake.updated_at|date:"Y-m-d H:i" }}
                            </small>
                        </div>
                        <button type="button" data-insert-mistake data-title="{{ mistake.title }}" data-url="{{ mistake.get_absolute_url }}" class="button small secondary">
                            插入链接
                        </button>
                    </div>
                </article>
                {% endfor %}
            </div>
        </div>
        {% endif %}

        <div style="display:flex;gap:1rem;flex-wrap:wrap;">
            <button class="button" type="submit" style="padding:0.75rem 1.75rem;">
                💾 保存笔记
            </button>
            <a class="button secondary" href="{% if is_edit %}{{ entry.get_absolute_url }}{% else %}{% url 'learning:notebook_list' %}{% endif %}" style="padding:0.75rem 1.75rem;">
                取消
            </a>
        </div>
    </form>
</section>

<script src="https://cdn.jsdelivr.net/npm/quill@1.3.7/dist/quill.min.js"></script>
{{ form.content.value|default_if_none:""|json_script:"initial-notebook-content" }}
<script>
    (function () {
        const form = document.getElementById("notebook-form");
        const textarea = document.getElementById("id_content");
        const initialNode = document.getElementById("initial-notebook-content");
        if (!form || !textarea) return;

        const quill = new Quill("#quill-editor", {
            theme: "snow",
            placeholder: "在这里撰写笔记内容……",
            modules: {
                toolbar: [
                    [{ header: [1, 2, 3, false] }],
                    ["bold", "italic", "underline", "strike"],
                    [{ list: "ordered" }, { list: "bullet" }],
                    ["blockquote", "code-block"],
                    [{ align: [] }],
                    ["link", "clean"]
                ],
            },
        });

        if (initialNode) {
            try {
                const initialContent = JSON.parse(initialNode.textContent || "\"\"");
                if (initialContent) {
                    quill.clipboard.dangerouslyPasteHTML(initialContent);
                }
            } catch (error) {
                console.warn("Failed to load initial notebook content:", error);
            }
        }

        const sync = () => {
            textarea.value = quill.root.innerHTML.trim();
        };

        quill.on("text-change", sync);
        form.addEventListener("submit", sync);

        const encodeHTML = (value) => value
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#39;");

        document.querySelectorAll("[data-insert-mistake]").forEach((button) => {
            button.addEventListener("click", (event) => {
                event.preventDefault();
                const title = button.dataset.title || "错题引用";
                const url = button.dataset.url || "#";
                const safeTitle = encodeHTML(title);
                const safeUrl = encodeURI(url);
                const snippet = `
                    <blockquote class="ql-indent-1">
                        <strong>错题引用：</strong>
                        <a href="${safeUrl}">${safeTitle}</a>
                    </blockquote>
                `.trim();
                const range = quill.getSelection(true);
                const index = range ? range.index : quill.getLength();
                quill.clipboard.dangerouslyPasteHTML(index, snippet, "user");
                quill.setSelection(index + 1);
                quill.focus();
                sync();
            });
        });
    })();
</script>
{% endblock %}
